var xlsx = require("node-xlsx");

var write = require('hy5b/backend/write');
var iconv = require('iconv-lite');
var out = write('out.csv');

function handleFile(filepath) {
    var list = xlsx.parse(filepath);

    var collection = {};

    for (var i = 0; i < list.length; i++) {
        var sheet = list[i];

        var name = sheet.name;
        var data = sheet.data;

        var row0 = data[0];
        var row0col0 = row0[0];
        var row0col1 = row0[1];

        for (var j = 1; j < data.length; j++) {
            var rowN = data[j]
            
            var rowNcol0 = rowN[0]
            var rowNcol1 = rowN[1]
            var key = rowNcol0;
            var value = rowNcol1;

            if (!collection[key]) {
                collection[key] = []
            }

            collection[key].push(value)
        }

        let maxValueLen = 0;
        for (var key in collection) {
            maxValueLen = Math.max(maxValueLen, collection[key].length);
        }

        let title0 = row0col0;
        let titleN = []

        for (var i = 0; i < maxValueLen; i++) {
            titleN.push(row0col1 + (i + 1));
        }

        var str = [title0, titleN.join(',')].join(',') + '\r\n';

        out.write(iconv.encode(str, 'gbk'));

        for (var key in collection) {
            str = [key, collection[key].join(',')].join(',') + '\r\n';
            out.write(iconv.encode(str, 'gbk'));
        }

    }
}

var filepath = './款号颜色.xlsx';

handleFile(filepath)